import * as types from '../mutations'

import http from '../../http'

const state = {
  vm: '',
  goods_list: [],
  total: 0,
  goods_types: [],
  goods_detail: {}
}

const getters = {
  goods_list: state => state.goods_list,
  total: state => state.total,
  goods_types: state => state.goods_types,
  goods_detail: state => state.goods_detail,
}

const mutations = {
  [types.SET_VM]: (state, payload) => {
    state.vm = payload.vm
  },
  [types.SET_GOODS_LIST]: (state, payload) => {
    state.goods_list = payload.data
  },
  [types.SET_TOTAL]: (state, payload) => {
    state.total = payload.object.total
  },
  [types.SET_CONTENT_LIST]: (state, payload) => {
    state.goods_types = payload
  },
  [types.SET_PRODUCT_DETAIL]: (state, payload) => {
    state.goods_detail = payload.product
  },
}

const actions = {
  get_goods_list({
    commit,
    dispatch,
    state
  }, payload) {
    http('/api/product/query_product', payload, function (res) {
      commit('SET_GOODS_LIST', res)
      commit('SET_TOTAL', res)
    })
  },
  goods_detail(context, payload) {
    http('/api/product/product_detail', payload, res => {
      context.commit(types.SET_PRODUCT_DETAIL, res.object)
    })
  },
  query_content(context, payload) {
    http('/api/config/query_content', {} ,res => {
      context.commit(types.SET_CONTENT_LIST, res.data)
    })
  },
  create_goods({
    commit,
    dispatch,
    state
  }, payload) {
    http('/api/product/create_product', payload, function (res) {
      if(res.code === 0){
        state.vm.$message.success(res.message)
      }else{
        state.vm.$message.success('添加失败')
      }
      dispatch('get_goods_list', state.vm.goodsSearch)
      state.vm.create_goods_visible = false
    })
  },
  modify_goods(context, payload) {
    var vm = context.state.vm
    http('/api/product/modify_product', payload.modify, function (res) {
      vm.$message.success(res.message)
      context.dispatch('get_goods_list', payload.goods_search)
    })
  },
  del_product(context, payload) {
    var vm = context.state.vm
    http('/api/product/del_product', payload.modify, res => {
      vm.$message.success(res.message)
      context.dispatch('get_goods_list', payload.goods_search)
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions

}
